package com.wx.finance.biz.config;

import com.alipay.remoting.BizContext;
import com.alipay.remoting.rpc.RpcServer;
import com.alipay.remoting.rpc.protocol.SyncUserProcessor;
import com.wx.common.dto.TokenResponse;
import com.wx.common.exception.BizException;
import com.wx.common.netty.NettyServerHelper;
import com.wx.common.sofabolt.SofaboltMsgResponse;
import com.wx.finance.biz.dto.form.msg.ScanSucMsgForm;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
@RequiredArgsConstructor
@Slf4j
public class WebSocketServerInitConfig implements CommandLineRunner {
    final NettyServerHelper nettyServerHelper;
    final RpcServer rpcServer;
    final ObjectMapper objectMapper;

    @Override
    public void run(String... args) {
        // 注册处理器
        rpcServer.registerUserProcessor(new SyncUserProcessor<ScanSucMsgForm>() {
            @Override
            public Object handleRequest(BizContext bizCtx, ScanSucMsgForm request) throws Exception {
                log.info("【收到客户端消息3】: {}，消息：{}", bizCtx.getConnection().getChannel().id().asLongText(),
                        request.toString());
                ChannelHandlerContext ctx = nettyServerHelper.onLineClients.get(request.getUserChannelId());
                if (ctx == null) {
                    throw new BizException("用户已下线：" + request.toString());
                }
                ctx.channel().writeAndFlush(new TextWebSocketFrame(objectMapper.writeValueAsString(request)));
                // 返回响应
                return new SofaboltMsgResponse("Hello " + bizCtx.getConnection().getChannel().id().asLongText());
            }

            @Override
            public String interest() {
                return ScanSucMsgForm.class.getName();
            }
        });
    }
}
